package main

import (
	"log"
	"net/http"

	"zwai-app/config"
	"zwai-app/db"
	"zwai-app/handlers"
)

func main() {
	cfg := config.Load()
	db.Init(cfg.MongoURI, cfg.MongoDB)
	defer db.Close()

	mux := http.NewServeMux()

	handlers.RegisterAuthRoutes(mux)
	handlers.RegisterLoginRoutes(mux, cfg)
	handlers.RegisterUserInfoRoutes(mux, cfg)
	handlers.RegisterArticleRoutes(mux, cfg)
	handlers.RegisterSMSRoutes(mux)
	handlers.RegisterUploadRoutes(mux, cfg)
	handlers.RegisterCategoryRoutes(mux, cfg)

	// CORS Wrapper
	corsMux := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusOK)
			return
		}
		mux.ServeHTTP(w, r)
	})

	addr := ":" + cfg.Port
	log.Printf("Server listening on %s", addr)
	if err := http.ListenAndServe(addr, corsMux); err != nil {
		log.Fatalf("ListenAndServe failed: %v", err)
	}
}
